package com.example.aigc_education.controller;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.aigc_education.anno.RequestKeyParam;
import com.example.aigc_education.anno.RequestLock;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.domain.Checklist;
import com.example.aigc_education.domain.dto.PageDTO;
import com.example.aigc_education.domain.request.*;
import com.example.aigc_education.domain.vo.ChecklistVO;
import com.example.aigc_education.domain.vo.UpdateChecklistViewVO;
import com.example.aigc_education.service.ChecklistService;
import com.example.aigc_education.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 待办控制器类，负责处理待办相关的HTTP请求。
 */
@Slf4j
@RequestMapping("/checkList")
@RestController
public class ChecklistController {
    @Resource
    private ChecklistService checkListService;




    /**
     * 添加待办
     * @param addChecklistRequest 添加待办DTO
     * @return 返回添加计划结果
     */
    @RequestLock(prefix = "addChecklist:",expire = 3)
    @PostMapping("/add")
    public ResultUtil addChecklist(@RequestKeyParam@RequestBody AddChecklistRequest addChecklistRequest){
        Checklist checklist = BeanUtil.copyProperties(addChecklistRequest, Checklist.class);
        if (checklist.getChecklistTitle() == null || StringUtils.isEmpty(checklist.getChecklistTitle())) {
            throw new IllegalArgumentException("待办标题不能为空");
        }
        if (checklist.getChecklistType() == null) {
            throw new IllegalArgumentException("待办类型不能为空");
        }
        if (checklist.getPriority() == null) {
            throw new IllegalArgumentException("待办优先级不能为空");
        }
        if (checklist.getDeadline().isBefore(LocalDateTime.now())) {
            throw new IllegalArgumentException("待办截止时间需要大于当前时间");
        }

//        checklist.setUserId(1L);
        checklist.setUserId(SecurityUtils.getUserId());
        boolean saved = checkListService.save(checklist);
        if (!saved) {
            throw new BusinessException("添加待办失败");
        }
        return ResultUtil.success();
    }




    /**
     * 获取待办（分页）
     * @param checklistQueryRequest 待办查询对象
     * @return 返回待办结果
     */
    @PostMapping("/page/getChecklists")
    public ResultUtil getChecklistsByPage (@RequestBody ChecklistQueryRequest checklistQueryRequest) {
        Long userId = SecurityUtils.getUserId();
//        Long userId = 1L;
        PageDTO<ChecklistVO> checklistPageDTO = checkListService.queryChecklistPage(userId, checklistQueryRequest);
        return ResultUtil.success(checklistPageDTO);
    }


    /**
     * 获取待办
     * @return 返回待办结果
     * 需要做分页查询
     */
    @GetMapping("/getChecklists")
    public ResultUtil getChecklists() {
//        Long userId = 1L;
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Checklist> queryWrapper = new LambdaQueryWrapper<>();
        //该用户的id
        queryWrapper.eq(Checklist::getUserId, userId);
        //将已完成待办筛掉
        queryWrapper.ne(Checklist::getChecklistStatus,2);
        queryWrapper.ne(Checklist::getChecklistStatus,4);
        // 根据待办优先级升序排序
        queryWrapper.orderByAsc(Checklist::getPriority);
        // 根据待办某日必做日期升序排序
        queryWrapper.orderByAsc(Checklist::getMustDoDay);
        List<Checklist> checklists = checkListService.list(queryWrapper);
        return ResultUtil.success(checklists);
    }

    @GetMapping("getTodayChecklists")
    public ResultUtil getTodayChecklists () {
//        Long userId = 1L;
        Long userId = SecurityUtils.getUserId();
        return  checkListService.getTodayChecklists(userId);
    }


    /**
     * 修改待办时的回显操作
     * @param checklistId 待办ID
     * @return 待办
     */
    @GetMapping("/{checklistId}")
    public ResultUtil getChecklistById(@PathVariable Long checklistId) {
        Checklist checklist = checkListService.getById(checklistId);
        UpdateChecklistViewVO updateChecklistViewVO = BeanUtil.copyProperties(checklist, UpdateChecklistViewVO.class);
        return ResultUtil.success(updateChecklistViewVO);
    }



    /**
     * 修改待办
     * @param updateChecklistRequest 修改后待办
     * @return 返回修改待办结果
     */
    @RequestLock(prefix = "updateChecklist:",expire = 3)
    @PutMapping("/update")
    public ResultUtil updateChecklistInfo(@RequestKeyParam @RequestBody UpdateChecklistRequest updateChecklistRequest) {
        return  checkListService.updateChecklistInfo(updateChecklistRequest);
    }




    /**
     * 删除待办
     * @param checklistId 待办id
     * @return 返回删除待办结果
     */
    @RequestLock(prefix = "deleteChecklist:",expire = 3)
    @DeleteMapping("/delete")
    public ResultUtil deleteChecklist(@RequestKeyParam Long checklistId) {
        log.info("com.example.aigc_education.controller.ChecklistController-deleteChecklist args:{}", checklistId);
        boolean removed = checkListService.removeById(checklistId);
        if (!removed) {
            throw new BusinessException("删除失败");
        }
        return ResultUtil.success("删除成功");
    }


    /**
     * 计时开始
     * @param checklistId 待办id
     * @return 成功200
     */
    @RequestLock(prefix = "timerStart:")
    @GetMapping("/Timer/start")
    public ResultUtil startTimer(@RequestKeyParam Long checklistId){
        return  checkListService.startTimer(checklistId);
    }


    /**
     * 修改计时状态
     * @param updateTimerRequest 计时状态
     * @return 返回修改待办结果
     */
    @RequestLock(prefix = "timerUpdate:",expire = 3)
    @PutMapping("/Timer/update")
    public ResultUtil updateTimingStatus(@RequestKeyParam @RequestBody UpdateTimerRequest updateTimerRequest) {
        return  checkListService.updateTimingStatus(updateTimerRequest);
    }


    @PutMapping("/Timer/test")
    public ResultUtil test(@RequestKeyParam @RequestBody UpdateTimerRequest updateTimerRequest) {
        return  ResultUtil.success("测试成功");
    }


    /**
     * 发送计时状态
     * @param checklistId 待办id
     * @return 返回修改待办结果
     */

    @GetMapping("/Timer/get")
    public ResultUtil getTimingStatus(Long checklistId) {
        return  checkListService.getTimingStatus(checklistId);
    }


    /**
     * 计时结束后修改待办数据
     * @param timerEndRequest 修改后待办
     * @return 返回修改待办结果
     */
    @RequestLock(prefix = "timerEnd:",expire = 3)
    @PutMapping("/Timer/end")
    public ResultUtil updateAfterTime(@RequestKeyParam @RequestBody TimerEndRequest timerEndRequest) {
        return  checkListService.updateAfterTime(timerEndRequest);
    }

}
